<template>
  <el-card class="box-card deployGroup" shadow="hover">
    <div slot="header" class="clearfix">
      <span>{{ deployGroup.showName }}
        <el-tag effect="dark" size="mini" type="success">{{ deployGroup.envType.name }}</el-tag>
        <el-tag v-if="deployGroup.gitBranch" effect="plain" size="mini" style="margin-left: 10px"
                type="success">{{ deployGroup.gitBranch }}</el-tag>
      </span>
      <div style="float: right;">
        <el-button size="mini" type="primary" @click="$parent.$refs.groupProps.openGroupProps(deployGroup.id)">分组配置
        </el-button>
      </div>
    </div>
    <el-row>
      <el-col :span="8" class="work-panel split-border">
        <div class="work-panel-title">代码构建</div>
        <div class="work-panel-content">
          <div class="btns">
            <el-button :loading="lastBuild.buildStatus&&lastBuild.buildStatus.code=='BUILDING'" size="mini"
                       type="success"
                       @click="onBuild()">构建
            </el-button>
            <el-button class="btn-right" size="mini" type="text"
                       @click="$router.push({name:'build',params:{'appName':deployGroup.appName}})">更多>>
            </el-button>
          </div>
          <div v-if="lastBuild.buildStatus" class="work-panel-info">
            <div class="work-panel-info-status">
              <el-progress :color="buildStatus.color" :percentage="buildStatus.percentage" :show-text="false"
                           :stroke-width="9"
                           :width="80"
                           type="circle"/>
              <div :style="'color:'+buildStatus.color" class="work-panel-status-name">{{ buildStatus.name }}</div>
            </div>
            <div class="work-panel-info-items">
              <div class="item">
                <div class="item-name">构建产物</div>
                <div class="item-value">
                  <div v-for="(a,i) in lastBuild.artifactList" :key="i">{{ a.artifactName }}</div>
                </div>
              </div>
              <div class="item">
                <div class="item-name">构建时间</div>
                <div class="item-value">{{ lastBuild.created }}</div>
              </div>
              <div class="item">
                <div class="item-name">操作人</div>
                <div class="item-value">{{ lastBuild.operatorName }}</div>
              </div>
            </div>
          </div>
          <div v-else class="work-panel-none">请先点击构建按钮完成代码构建</div>
        </div>
      </el-col>
      <el-col :span="8" class="work-panel split-border">
        <div class="work-panel-title">发布申请</div>
        <div class="work-panel-content">
          <div class="btns">
            <el-button v-if="deployApply.applyStatus==null||deployApply.applyStatus.code!='AUDITING'" size="mini"
                       type="primary" @click="onApply()">申请
            </el-button>
            <el-button v-else size="mini"
                       type="warning" @click="onCancelApply()">取消
            </el-button>
            <el-button class="btn-right" size="mini" type="text"
                       @click="$router.push({name:'applyList'})">更多>>
            </el-button>
          </div>
          <div v-if="deployApply.applyStatus" class="work-panel-info">
            <div class="work-panel-info-status">
              <el-progress :color="applyStatus.color" :percentage="100" :show-text="false" :stroke-width="9" :width="80"
                           type="circle"/>
              <div :style="'color:'+applyStatus.color" class="work-panel-status-name">{{ applyStatus.name }}</div>
            </div>
            <div class="work-panel-info-items">
              <div v-if="deployApply.applyFormData" class="item">
                <div class="item-name">发布内容</div>
                <div class="item-value">{{ deployApply.remark }}</div>
              </div>
              <div v-if="deployApply.applyFormData" class="item">
                <div class="item-name">发布包</div>
                <div class="item-value">{{ deployApply.applyFormData.artifact.artifactName }}</div>
              </div>
              <div class="item">
                <div class="item-name">申请时间</div>
                <div class="item-value">{{ deployApply.created }}</div>
              </div>
              <div class="item">
                <div class="item-name">申请人</div>
                <div class="item-value">{{ deployApply.applyUserName }}</div>
              </div>
            </div>
          </div>
          <div v-else class="work-panel-none">点击申请按钮进行发布申请</div>
        </div>
      </el-col>
      <el-col :span="8" class="work-panel">
        <div class="work-panel-title">实例发布</div>
        <div class="work-panel-content">
          <div class="btns">
            <el-button :disabled="deployGroup.deployStatus.code != 'DEPLOYING'" :loading="deployLoading"
                       size="mini"
                       type="primary"
                       @click="onDeploy"
            >发布
            </el-button>
            <el-button v-if="deployGroup.deployStatus.code == 'DEPLOYING'" size="mini" style="color: #E6A23C"
                       type="text"
                       @click="onCloseGroupDeploy">关闭发布
            </el-button>
            <el-button class="btn-right" size="mini" type="text" @click="onInstances">实例</el-button>
          </div>
          <div v-if="deployGroup.deployStatus.code!='WAITING'&&deployGroup.deployStatus.code!='NONE'"
               class="work-panel-info">
            <div class="work-panel-info-status">
              <el-progress :color="deployStatus.color" :percentage="deployStatus.percentage" :show-text="false"
                           :stroke-width="9"
                           :width="80"
                           type="circle"/>
              <div :style="'color:'+deployStatus.color" class="work-panel-status-name">{{ deployStatus.name }}</div>
            </div>
            <div class="work-panel-info-items">
              <div class="item">
                <div class="item-name">发布状态</div>
                <div class="item-value">
                  <el-tag :type="tagType(deployGroup.deployStatus.code)" size="mini">
                    {{ deployGroup.deployStatus.name }}
                  </el-tag>

                </div>
              </div>
              <div class="item">
                <div class="item-name">实例状态</div>
                <div class="item-value">
                  <el-link v-for="(stat,i) in deployStats" :key="i" :type="stat.type" :underline="false"
                           style="margin-right: 5px;font-size: 12px;line-height: 22px">
                    {{ stat.name }}:{{ stat.num }}
                  </el-link>
                </div>
              </div>
              <div class="item">
                <div class="item-name">发布时间</div>
                <div class="item-value">{{ lastDeployRecord.endTime }}</div>
              </div>
              <div class="item">
                <div class="item-name">发布人</div>
                <div class="item-value">{{ lastDeployRecord.operatorName }}</div>
              </div>
            </div>
          </div>
          <div v-else class="work-panel-none">请先完成发布申请</div>
        </div>
      </el-col>
    </el-row>
  </el-card>
</template>
<script>
import {buildApi, lastBuildApi} from "@/api/build";
import {applyDetailApi, cancelApplyApi} from "@/api/apply";
import {appInstanceListApi, closeGroupDeployApi} from "@/api/manage";
import {deployByGroupApi, lastRecordByGroupApi} from "@/api/deploy";

export default {
  props: {
    deployGroup: {},
  },
  data() {
    return {
      lastBuild: {},
      lastDeployRecord: {},
      deployApply: {},
      instances: [],
      buildStatusColor: {
        'WAITING': '#909399',
        'BUILDING': '#409EFF',
        'BUILD_SUCCESS': '#67C23A',
        'BUILD_FAIL': '#F56C6C'
      },
      applyStatusColor: {
        'SUBMIT': '#409EFF',
        'AUDITING': '#409EFF',
        'CANCEL': '#E6A23C',
        'APPROVE': '#67C23A',
        'REJECT': '#F56C6C'
      },
      deployStatusColor: {
        'NONE': '#909399',
        'WAITING': '#909399',
        'DEPLOYING': '#409EFF',
        'DEPLOY_SUCCESS': '#67C23A',
        'DEPLOY_FAIL': '#F56C6C'
      },
    };
  },
  watch: {
    deployGroup() {
      this.loadDeployApply();
    },
    lastBuild(data) {
      if (data && data.buildStatus && data.buildStatus.code == "BUILDING") {
        setTimeout(this.loadLastBuild, 1000 * 2);
      }
    },
  },
  computed: {
    buildStatus() {
      let s = {color: '', name: '', percentage: 100};
      if (this.lastBuild.buildStatus) {
        s.color = this.buildStatusColor[this.lastBuild.buildStatus.code];
        s.name = this.lastBuild.buildStatus.name;
      }
      return s;
    },
    applyStatus() {
      let s = {color: '', name: ''};
      if (this.deployApply.applyStatus) {
        s.name = this.deployApply.applyStatus.name;
        s.color = this.applyStatusColor[this.deployApply.applyStatus.code];
      }
      return s;
    },
    deployStatus() {
      let s = {color: '', name: '', percentage: 100};
      if (this.deployGroup.deployStatus && this.lastDeployRecord.id) {
        if (this.deployGroup.deployStatus.code == 'DEPLOYING' && this.instances.length > 0) {
          s.name = this.deployGroup.deployStatus.name;
          s.color = this.deployStatusColor[this.deployGroup.deployStatus.code];
          let num = this.instances.filter(i => i.deployStatus.code == 'DEPLOYING').length;
          s.percentage = ((this.instances.length - num) / this.instances.length) * 100;
          if (num == 0) {
            if (this.instances.filter(i => i.deployStatus.code == 'DEPLOY_SUCCESS').length > 0) {
              s.name = '发布成功';
              s.color = this.deployStatusColor['DEPLOY_SUCCESS'];
            }
            if (this.instances.filter(i => i.deployStatus.code == 'DEPLOY_FAIL').length > 0) {
              s.name = '发布失败';
              s.color = this.deployStatusColor['DEPLOY_FAIL'];
            }
          }
        }
      }
      return s;
    },
    deployLoading() {
      return this.instances.filter(i => i.deployStatus.code == 'DEPLOYING').length > 0;
    },
    deployStats() {
      let stat = [];
      stat.push({name: "总数", type: "primary", num: this.instances.length});
      if (this.lastDeployRecord.id) {
        stat.push({
          name: "发布中",
          type: "warning",
          num: this.instances.filter(i => i.deployStatus.code == 'DEPLOYING').length
        });
        stat.push({
          name: "成功",
          type: "success",
          num: this.instances.filter(i => i.deployStatus.code == 'DEPLOY_SUCCESS').length
        });
        stat.push({
          name: "失败",
          type: "danger",
          num: this.instances.filter(i => i.deployStatus.code == 'DEPLOY_FAIL').length
        });
      }
      return stat.filter(s => s.num > 0);
    },
  },
  methods: {
    tagType(code) {
      if (code == 'DEPLOY_SUCCESS' || code == 'APPROVE' || code == 'BUILD_SUCCESS') {
        return 'success';
      } else if (code == 'DEPLOY_FAIL' || code == 'REJECT' || code == 'BUILD_FAIL') {
        return 'danger';
      } else if (code == 'DEPLOYING' || code == 'AUDITING' || code == 'BUILDING') {
        return 'warning';
      } else if (code == 'NONE' || code == 'CANCEL') {
        return 'info';
      }
      return 'primary'
    },
    async loadLastBuild() {
      let data = await lastBuildApi(this.deployGroup.appName, this.deployGroup.gitBranch);
      this.lastBuild = data == null ? {} : data;
    },
    async loadDeployApply() {
      this.deployApply = {};
      if (this.deployGroup.applyId != null) {
        this.deployApply = await applyDetailApi(this.deployGroup.applyId);
      }
    },
    async loadAppInstances() {
      this.instances = await appInstanceListApi(this.deployGroup.appName, this.deployGroup.name);
    },
    loadLastRecord() {
      lastRecordByGroupApi(this.deployGroup.id).then((data) => {
        if (data != null) this.lastDeployRecord = data;
      });
    },
    onBuild() {
      buildApi(this.deployGroup.appName, this.deployGroup.gitBranch)
          .then(() => this.loadLastBuild());
    },
    onInstances() {
      this.$parent.$refs.instanceDialog.open(this.deployGroup, this.instances);
    },
    async onApply() {
      this.$parent.$refs.applyDialog.open(this.deployGroup);
    },
    async onCancelApply() {
      await cancelApplyApi(this.deployGroup.applyId);
      this.$message({message: `取消成功`, type: "success",});
      this.$parent.loadDeployGroups();
    },
    onDeploy() {
      this.$confirm('是否批量发布所有实例？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deployByGroupApi(this.deployGroup.id)
            .then(() => {
              this.$message({message: `提交发布成功`, type: "success",});
              this.loadAppInstances();
            });
      });
    },
    onCloseGroupDeploy() {
      this.$confirm('是否关闭本次发布？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        closeGroupDeployApi(this.deployGroup.id)
            .then(() => {
              this.$message({message: `提交关闭成功`, type: "success",});
              this.$parent.loadDeployGroups();
            });
      });
    }
  },
  mounted() {
    const that = this;
    this.timer = setInterval(function () {
      if (that.deployGroup.deployStatus.code == 'DEPLOYING') {
        that.loadAppInstances();
        that.loadLastRecord();
      }
    }, 2000);
  },
  created() {
    this.loadLastBuild();
    this.loadDeployApply();
    this.loadAppInstances();
    this.loadLastRecord();
  },
  destroyed() {
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
};
</script>
<style scoped>
.deployGroup /deep/ .el-card__body {
  padding: 0px;
}

.deployGroup .work-panel {
  font-size: 12px;
  min-height: 200px;
}

.deployGroup .work-panel .work-panel-title {
  font-size: 14px;
  font-weight: bold;
  height: 40px;
  line-height: 40px;
  border-bottom: 1px #EBEEF5 solid;
  color: #303133;
  text-align: center;
  color: #409EFF;
}

.deployGroup .work-panel .work-panel-content {
  padding: 10px;
}

.deployGroup .split-border {
  border-right: 1px #EBEEF5 solid;
}

.deployGroup .work-panel-info {
  display: flex;
  flex-flow: row nowrap;
}

.deployGroup .work-panel-info .work-panel-info-status {
  width: 80px;
  position: relative;
}

.deployGroup .work-panel-info .work-panel-info-status .work-panel-status-name {
  position: absolute;
  text-align: center;
  vertical-align: middle;
  font-size: 13px;
  width: 80px;
  top: 30px;
}

.deployGroup .work-panel-info .work-panel-info-items {

}

.deployGroup .work-panel-none {
  width: 100%;
  padding-top: 20px;
  text-align: center;
  vertical-align: middle;
  font-size: 15px;
  color: #909399;
}

.deployGroup .btns {
  height: 50px;
  text-align: center;
  position: relative;
}

.deployGroup .btn-right {
  position: absolute;
  right: 5px;
}

.deployGroup .item {
  display: block;
  min-height: 22px;
  line-height: 22px;
}

.deployGroup .item .item-name {
  width: 60px;
  float: left;
  text-align: right;
  color: #606266;
}

.deployGroup .item .item-value {
  margin-left: 70px;
  min-width: 100px;
  position: relative;
  color: #000000;
}
</style>
